<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <br />
        <!-- 卡片试图区域 -->
        <el-card>
            <!-- 搜索与添加区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input
                        placeholder="请输入内容"
                        v-model="queryInfo.query"
                        clearable
                        @clear="getUserList"
                    >
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户列表区域 -->
            <el-table :data="userList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <template v-slot="scope">
                        <el-switch
                            v-model="scope.row.mg_state"
                            @change="userStateChange(scope.row)"
                        ></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="scope">
                        <el-row>
                            <el-tooltip content="修改" placement="top" effect="dark">
                                <el-button
                                    title="修改"
                                    type="primary"
                                    icon="el-icon-edit"
                                    circle
                                    size="small"
                                    @click="showEditDialog(scope.row.id)"
                                ></el-button>
                            </el-tooltip>
                            <el-tooltip content="分配角色" placement="top" effect="dark">
                                <el-button
                                    type="success"
                                    icon="el-icon-setting"
                                    circle
                                    size="small"
                                    @click="showSetRole(scope.row)"
                                ></el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top" effect="dark">
                                <el-button
                                    type="danger"
                                    icon="el-icon-delete"
                                    circle
                                    size="small"
                                    @click="del(scope.row.id)"
                                ></el-button>
                            </el-tooltip>
                        </el-row>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1,2,5,10]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            ></el-pagination>
        </el-card>

        <!-- 修改用户对话框 -->
        <el-dialog
            title="修改用户"
            :visible.sync="editDialogVisible"
            width="50%"
            @close="editDialogClosed"
        >
            <el-form :model="editForm" ref="editFormRef" :rules="editFormRules" label-width="80px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
            <el-form :model="addForm" ref="addFormRef" :rules="addFormRules" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog title="分配角色" :visible.sync="setRoleDialog"
        @close="setRolesDialogClosed" width="50%">
            <div>
                <p>当前的用户:{{userInfo.username}}</p>
                <p>当前的角色:{{userInfo.role_name}}</p>
                <p>
                    分配新角色：
                    <el-select v-model="selectedRoleId" placeholder="请选择角色">
                        <el-option
                            v-for="item in roleList"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer">
                <el-button @click=" setRoleDialog= false">取 消</el-button>
                <el-button type="primary" @click="saveRolesInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        var checkEmail = (rule, value, cb) => {
            const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
            if (regEmail.test(value)) return cb();
            cb(new Error("请输入合法的邮箱"));
        };
        var checkMobile = (rule, value, cb) => {
            const regMobile = /^1[3456789]\d{9}$/;
            if (regMobile.test(value)) return cb();
            cb(new Error("请输入正确的手机号"));
        };
        return {
            queryInfo: {
                query: "",
                pagenum: 1,
                pagesize: 10
            },
            userList: [],
            total: 0,
            dialogVisible: false,
            editDialogVisible: false,
            addForm: {
                username: "",
                password: "",
                email: "",
                mobile: ""
            },
            editForm: {},
            addFormRules: {
                username: [
                    {
                        required: true,
                        message: "请输入用户名",
                        trigger: "blur"
                    },
                    {
                        min: 5,
                        max: 15,
                        message: "请输入5-15个字符",
                        trigger: "blur"
                    }
                ],
                password: [
                    { required: true, message: "请输入密码", trigger: "blur" },
                    {
                        min: 5,
                        max: 15,
                        message: "请输入5-15个字符",
                        trigger: "blur"
                    }
                ],
                email: [
                    { required: true, message: "请输入邮箱", trigger: "blur" },
                    { validator: checkEmail, trigger: "blur" }
                ],
                mobile: [
                    { required: true, message: "请输入手机", trigger: "blur" },
                    { validator: checkMobile, trigger: "blur" }
                ]
            },
            editFormRules: {
                email: [
                    { required: true, message: "请输入邮箱", trigger: "blur" },
                    { validator: checkEmail, trigger: "blur" }
                ],
                mobile: [
                    { required: true, message: "请输入手机", trigger: "blur" },
                    { validator: checkMobile, trigger: "blur" }
                ]
            },
            setRoleDialog: false,
            userInfo: [],
            roleList: [],
            selectedRoleId: ""
        };
    },
    created() {
        this.getUserList();
    },
    methods: {
        getUserList() {
            this.$axios.get("users", { params: this.queryInfo }).then(res => {
                this.userList = res.data.data.users;
                this.total = res.data.data.total;
            });
        },
        handleSizeChange(newSize) {
            this.queryInfo.pagesize = newSize;
            this.getUserList();
        },
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage;
            this.getUserList();
        },
        userStateChange(userinfo) {
            this.$axios
                .put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
                .then(res => {
                    let resp = res.data;
                    if (resp.meta.status !== 200) {
                        userinfo.mg_state = !userinfo.mg_state;
                        return this.$message.error("更新用户状态失败!");
                    }
                    this.$message.success("更新用户状态成功!");
                });
        },
        addDialogClosed() {
            this.$refs.addFormRef.resetFields();
        },
        addUser() {
            this.$refs.addFormRef.validate(valid => {
                if (!valid) return;
                this.$axios.post("users", this.addForm).then(res => {
                    let resp = res.data;
                    if (resp.meta.status !== 201) {
                        return this.$message({
                            message: "添加用户失败！",
                            type: "error"
                        });
                    }
                    this.$message({
                        message: "添加用户成功!",
                        type: "success"
                    });
                    this.dialogVisible = false;
                    this.getUserList();
                });
            });
        },
        showEditDialog(id) {
            this.editDialogVisible = true;
            this.$axios.get(`users/${id}`).then(response => {
                let res = response.data;
                if (res.meta.status !== 200)
                    return this.$message({
                        message: "查询用户信息失败",
                        type: "error",
                        showClose: true
                    });
                this.editForm = res.data;
            });
        },
        editDialogClosed() {
            this.$refs.editFormRef.resetFields();
        },
        editUserInfo() {
            this.$refs.editFormRef.validate(valid => {
                if (!valid) return;
                this.$axios
                    .put(`users/${this.editForm.id}`, this.editForm)
                    .then(response => {
                        let res = response.data;
                        if (res.meta.status !== 200)
                            return this.$message({
                                message: "修改失败!",
                                type: "error",
                                showClose: true
                            });
                        this.$message({
                            message: "修改成功！",
                            type: "success",
                            showClose: true
                        });
                        this.editDialogVisible = false;
                        this.getUserList();
                    });
            });
        },
        del(id) {
            this.$confirm("是否确认删除该用户?", "删除用户", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                callback: action => {
                    if (action !== "confirm") return;
                    this.$axios.delete(`users/${id}`).then(response => {
                        let res = response.data;
                        if (res.meta.status !== 200)
                            return this.$message({
                                message: "删除失败!",
                                type: "error",
                                showClose: true
                            });
                        this.$message({
                            message: "删除成功",
                            type: "success",
                            showClose: true
                        });
                        this.getUserList();
                    });
                }
            });
        },
        showSetRole(userInfo) {
            this.userInfo = userInfo;
            this.setRoleDialog = true;
            this.$axios.get("roles").then(response => {
                let res = response.data;
                if (res.meta.status !== 200)
                    return this.$message({
                        message: "获取角色列表失败！",
                        type: "error",
                        showClose: true
                    });
                this.roleList = res.data;
            });
        },
        saveRolesInfo() {
            if (!this.selectedRoleId)
                return this.$message({
                    message: "请选择要分配的角色",
                    type: "error",
                    showClose: true
                });
            this.$axios
                .put(`users/${this.userInfo.id}/role`, {
                    rid: this.selectedRoleId
                })
                .then(response => {
                    let res = response.data;
                    console.log(res)
                    if (res.meta.status !== 200)
                        return this.$message({
                            message: "分配角色失败!",
                            type: "error",
                            showClose: true
                        });
                    this.$message({
                        message: '更新角色成功！',
                        type: 'success',
                        showClose: true,
                    });
                    this.getUserList();
                    this.setRoleDialog=false
                });
        },
        setRolesDialogClosed(){
            this.selectedRoleId=''
            this.userInfo=[]
        }
    }
};
</script>
<style lang="less" scoped>
</style>